package com.petcommunity.servlet;

import com.petcommunity.dao.VaccineRecordDAO;
import com.petcommunity.model.VaccineRecord;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

@WebServlet("/vaccines")
public class VaccineRecordServlet extends HttpServlet {

    private VaccineRecordDAO vaccineRecordDAO = new VaccineRecordDAO();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<VaccineRecord> records = vaccineRecordDAO.getAllRecords();
        request.setAttribute("records", records);
        request.getRequestDispatcher("vaccines.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            VaccineRecord record = new VaccineRecord();
            record.setPetId(Integer.parseInt(request.getParameter("petId")));
            record.setVaccineName(request.getParameter("vaccineName"));
            record.setVaccinationDate(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("vaccinationDate")));
            record.setNextDueDate(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("nextDueDate")));

            vaccineRecordDAO.addRecord(record);
            response.sendRedirect("vaccines");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("error.jsp");
        }
    }
}

